// 最稳定、最兼容 鸿蒙 + 安卓的 APK 下载（系统通知栏）版
export function downloadApk(url, appStoreUrl, fileName = '绿港云.apk') {
  return new Promise((resolve, reject) => {
    const sysInfo = uni.getSystemInfoSync()

    // iOS
    if (sysInfo.platform === 'ios') {
      plus.runtime.launchApplication({ action: appStoreUrl }, (e) => {
        console.log('Open system default browser failed: ' + e.message)
        reject(new Error('iOS 打开 App Store 失败'))
      })
      return resolve('iOS 已跳转 App Store')
    }

    // 安卓 和 鸿蒙
    const context = plus.android.runtimeMainActivity()
    const Uri = plus.android.importClass('android.net.Uri')
    const Intent = plus.android.importClass('android.content.Intent')
    const Build = plus.android.importClass('android.os.Build')
    const File = plus.android.importClass('java.io.File')
    const DownloadManager = plus.android.importClass(
      'android.app.DownloadManager'
    )
    const Environment = plus.android.importClass('android.os.Environment')

    try {
      const downloadManager = context.getSystemService(context.DOWNLOAD_SERVICE)
      const uri = Uri.parse(url)

      // 保存到专属目录（不会需要存储权限）
      const file = new File(
        context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
        fileName
      )
      if (file.exists()) file['delete']()

      const request = new DownloadManager.Request(uri)
      request.setTitle('绿港云应用更新')
      request.setDescription('正在下载绿港云最新版本...')
      request.setDestinationUri(Uri.fromFile(file))
      request.setAllowedOverRoaming(true)
      request.setMimeType('application/vnd.android.package-archive')
      request.setNotificationVisibility(
        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
      )

      const downloadId = downloadManager.enqueue(request)

      uni.showToast({
        title: '后台下载已开始，请在通知栏查看进度',
        duration: 2000,
        icon: 'none',
      })

      resolve('后台下载已开始')

      // === 监听下载完成 ===
      const receiver = plus.android.implements(
        'io.dcloud.android.content.BroadcastReceiver',
        {
          onReceive(ctx, intent) {
            const id = intent.getLongExtra(
              DownloadManager.EXTRA_DOWNLOAD_ID,
              -1
            )
            if (id !== downloadId) return

            let installIntent = new Intent(Intent.ACTION_VIEW)
            let apkUri

            if (Build.VERSION.SDK_INT >= 24) {
              const FileProvider = plus.android.importClass(
                'androidx.core.content.FileProvider'
              )
              apkUri = FileProvider.getUriForFile(
                ctx,
                ctx.getPackageName() + '.fileprovider',
                file
              )
              installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            } else {
              apkUri = Uri.fromFile(file)
              installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }

            installIntent.setDataAndType(
              apkUri,
              'application/vnd.android.package-archive'
            )

            ctx.startActivity(installIntent)

            ctx.unregisterReceiver(receiver)
          },
        }
      )

      const IntentFilter = plus.android.importClass(
        'android.content.IntentFilter'
      )
      const filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
      context.registerReceiver(receiver, filter)
    } catch (e) {
      console.error(e)
      reject(e)
    }
  })
}
